package com.bawei.detail.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bawei.image.ImageOptions
import com.bawei.image.ImageStrategy
import com.bawei.image.ImgLoader
import com.bawei.common.entity.MovieEntity
import com.bawei.detail.databinding.ItemDetailLayoutBinding
import com.bumptech.glide.Glide

class DetailMovieListAdapter constructor(private val list: MutableList<MovieEntity>): RecyclerView.Adapter<DetailMovieListAdapter.MovieViewHolder>(){

    //图片框架
    private var imgLoader: ImgLoader = ImgLoader.Builder.setImageStrategy(ImageStrategy.GLIDE).build()

    private var itemClickListener: OnItemClickListener? = null


    //普通图片参数
    private var imgOption: ImageOptions = ImageOptions.Builder
        .setImageSize(intArrayOf(80, 80))
        .setCircleImage(false)
        .skipMemoryCache(true)
        .build()

    inner class MovieViewHolder(val dataBinding: ItemDetailLayoutBinding) : RecyclerView.ViewHolder(dataBinding.root)

    //设置Item点击事件
    fun setOnItemClickListener(listener: OnItemClickListener){
        itemClickListener = listener
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
        return MovieViewHolder(ItemDetailLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false))
    }

    override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
        val entity = list[position]
        var movieImg = holder.dataBinding.ivMovieImg
        imgLoader.loadUrlIntoImageView(holder.dataBinding.root.context, entity.videomainimag, movieImg, imgOption)
        holder.dataBinding.tvMovieDesc.text = entity.description
        holder.dataBinding.tvPlayCount.text = "${entity.favoritecount + 321}次播放"
        holder.dataBinding.root.setOnClickListener{
            itemClickListener?.onItemChildClick(it, position)
        }
    }

    /**
     * 当前View回收后，将图片组件从Glide中清除掉
     */
    override fun onViewRecycled(holder: MovieViewHolder) {
        var movieImg = holder.dataBinding.ivMovieImg
        Glide.with(holder.dataBinding.root.context).clear(movieImg)
    }

    override fun getItemCount(): Int = list.size

    override fun getItemViewType(position: Int): Int {
        return 0
    }

    override fun getItemId(position: Int): Long {
        return list[position].id.toLong()
    }

    /**
     * 点击事件接口类
     */
    interface OnItemClickListener {
        fun onItemChildClick(v: View?, position: Int)
    }

}